import React,{Component} from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { HeaderWrap, Logo, Nav, NavItem,
  SearchInput, Button, Addition, SearchWrapper,
  SearchContent, SearchInfo, SearchItem, SearchSwitch,
  SearchTitle, SearchTop
} from './style'
import { actionCreator } from './store'
import { actionCreator as logout } from '../../pages/login/store';


class Header extends Component {
  constructor(props) {
    super(props);
  }

  getSearchInfo = () => {
    let { page, totalPage, list, focused, mouseIn  } = this.props;
    let newList = list.toJS(); // 把immutable对象转为普通js对象
    let pageList = [];
    if (newList.length) {  // 防止没有数据时，此时page=1，依旧会循环数据
      for (let i = (page - 1) * 5; i < page * 5; ++i) {
        pageList.push(<SearchItem key={newList[i]}>{newList[i]}</SearchItem>);
      }
    }

    if (focused || mouseIn) {
      return (
        <SearchInfo
          onMouseEnter={this.props.handleMouseEnter}
          onMouseLeave={this.props.handleMouseLeave}
        >
          <SearchTitle>
            <SearchTop>热门搜索</SearchTop>
            {/*下面这个无法传递page，要使用箭头函数在里面传值*/}
            {/*<SearchSwitch onClick={this.props.handlePage.bind(page)}>换一批</SearchSwitch>*/}
            <SearchSwitch onClick={() => {this.props.handlePage(page, totalPage, this.SpinIcon)}}>
              <i className="iconfont spin"
                 ref={(icon) => {this.SpinIcon = icon}}>&#xe7e9;</i>
              换一批
            </SearchSwitch>
          </SearchTitle>
          <SearchContent>
            {
              pageList.map((item) => {
                return item
              })
            }
          </SearchContent>
        </SearchInfo>
      )
    }
  };

  render() {
    return (
      <HeaderWrap>
        <Link to="/">
          <Logo />
        </Link>
        <Nav>
          <NavItem className="left active">首页</NavItem>
          <NavItem className="left">下载App</NavItem>
          {
            !this.props.login ?
              <Link to="/login"><NavItem className="right">登录</NavItem></Link> :
              <NavItem className="right" onClick={this.props.logout}>退出</NavItem>
          }
          <NavItem className="right">
            <i className="iconfont">&#xe636;</i>
          </NavItem>
          <SearchWrapper>
            <SearchInput
              className={this.props.focused ? 'focused' : ''}
              onFocus={() => {this.props.inputFocus(this.props.list)}}
              onBlur={this.props.inputBlur}
            />
            <i className={this.props.focused ? 'focused iconfont zoom' : 'iconfont zoom'}>&#xe617;</i>
            {this.getSearchInfo()}
          </SearchWrapper>
        </Nav>
        <Addition>
          <Link to="/write">
            <Button className="write">
              <i className="iconfont">&#xe615;</i>
              写文章
            </Button>
          </Link>
          <Button className="register">注册</Button>
        </Addition>
      </HeaderWrap>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    // focused: state.header.get('focused')  没有加redux-immutable，只有immutable的用法
    // focused: state.get('header').get('focused')  加redux-immutable把state变为了immutable对象
    focused: state.getIn(['header','focused']),
    list: state.getIn(['header', 'list']),
    mouseIn: state.getIn(['header', 'mouseIn']),
    page: state.getIn(['header', 'page']),
    totalPage: state.getIn(['header', 'totalPage']),
    login: state.getIn(['login', 'login'])
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    inputFocus(list) {
      // 通过传递过来的list的size判断是否需要加载ajax
      list.size === 0 && dispatch(actionCreator.changeListAction());
      dispatch(actionCreator.focusAction)
    },
    inputBlur() {
      dispatch(actionCreator.blurAction);
    },
    handleMouseEnter() {
      dispatch(actionCreator.mouseEnter());
    },
    handleMouseLeave() {
      dispatch(actionCreator.mouseLeave())
    },
    handlePage (page, totalPage, span) {
      let angel = span.style.transform.replace(/[^0-9]/ig, ''); // 【注意】^的两种用法。一:限定开头。二：（否）取反
      if (!angel) {
        angel = 0
      }
      span.style.transform = 'rotate(' + (parseInt(angel) + 360) +'deg)';
      page = page < totalPage ? 1+ page : 1;
      dispatch(actionCreator.changePage(page))
    },
    logout () {
      dispatch(logout.logout())
    }
  }
};


export default connect(mapStateToProps, mapDispatchToProps)(Header);